package com.jlnk.androidfmc.view;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.database.NewDatabaseHelper;
import com.jlnk.androidfmc.entity.News;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;

public class NewsPost extends AppCompatActivity {

    private EditText titleEditText, contentEditText;
    private ImageView selectedImage;
    private Button postButton, buttonChooseImage;
    private static final int IMAGE_PICK_CODE = 100;
    static final int REQUEST_STORAGE_PERMISSION_CODE = 101;
    private Uri selectedImageUri;
    private static final String COLUMN_TITLE = "title";
    private static final String COLUMN_CONTENT = "content";
    private static final String COLUMN_IMAGE = "image";
    private static final String TABLE_NEWS = "news";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_post);

        // 初始化控件
        titleEditText = findViewById(R.id.titleEditText);
        contentEditText = findViewById(R.id.contentEditText);
        selectedImage = findViewById(R.id.selectedImage);
        postButton = findViewById(R.id.postButton);
        buttonChooseImage = findViewById(R.id.buttonChooseImage);

        // 设置发布按钮的点击监听器
        postButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取用户输入的数据
                String title = titleEditText.getText().toString();
                String content = contentEditText.getText().toString();
                Bitmap imageBitmap = selectedImage.getDrawable() instanceof BitmapDrawable ? ((BitmapDrawable) selectedImage.getDrawable()).getBitmap() : null;

                // 检查标题和内容是否为空
                if (!title.isEmpty() && !content.isEmpty()) {
                    // 用户没有选择图片时，imageBitmap 保持为 null
                    boolean isInserted = insertNewsIntoDatabase(title, content, imageBitmap);

                    // 根据插入结果提示用户
                    if (isInserted) {
                        Toast.makeText(NewsPost.this, "发布成功", Toast.LENGTH_SHORT).show();
                        // 清空输入框
                        titleEditText.setText("");
                        contentEditText.setText("");
                        selectedImage.setImageResource(0); // 清除已选择的图片

                        // 创建一个新的 News 对象并放入 Intent 中
                        News newNews = new News();
                        newNews.setTitle(title);
                        newNews.setContent(content);
                        if (imageBitmap != null) {
                            newNews.setImage(imageBitmap); // 存储 Bitmap 对象
                        }
                        Intent resultIntent = new Intent();
                        resultIntent.putExtra("new_news", newNews);
                        setResult(RESULT_OK, resultIntent);
                        finish();
                    } else {
                        Toast.makeText(NewsPost.this, "发布失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(NewsPost.this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 设置图片选择区域的点击监听器
        buttonChooseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseImage();
            }
        });
    }

    private void chooseImage() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            requestStoragePermission();
        } else {
            openImagePicker();
        }
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_PICK_CODE);
    }

    private void requestStoragePermission() {
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_STORAGE_PERMISSION_CODE
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openImagePicker();
            } else {
                Toast.makeText(this, "需要存储权限来选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            // 用户成功选择了图片
            selectedImageUri = data.getData();
            try {
                // 设置ImageView显示选中的图片
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                selectedImage.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "图片加载失败，请重试", Toast.LENGTH_SHORT).show();
                // 可以选择重置selectedImageUri为null或显示一个默认图片
                selectedImageUri = null;
                selectedImage.setImageResource(R.drawable.n4); // 替换为一个默认图片
            }
        }
    }

    private Bitmap getBitmapFromUri(Uri uri) {
        if (uri == null) {
            // 处理 uri 为 null 的情况，例如显示一个默认图片或返回 null
            Toast.makeText(this, "图片链接为空", Toast.LENGTH_SHORT).show();
            return null;
        }
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            return BitmapFactory.decodeStream(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "图片文件未找到", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    private boolean insertNewsIntoDatabase(String title, String content, Bitmap imageBitmap) {
        SQLiteDatabase db = new NewDatabaseHelper(this).getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_TITLE, title);
        values.put(COLUMN_CONTENT, content);
        if (imageBitmap != null) {
            values.put(COLUMN_IMAGE, convertBitmapToByteArray(imageBitmap)); // 存储图片数据
        }

        long newRowId = db.insert(TABLE_NEWS, null, values);
        db.close();
        Log.d("NewsPost", "Insertion result: " + (newRowId != -1));
        return newRowId != -1;
    }

    private byte[] convertBitmapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        return outputStream.toByteArray();
    }
}